package com.cn.steam.foundation.common.web.config.jwt;

import com.cn.steam.foundation.common.web.model.ServiceContext;
import org.slf4j.MDC;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import static com.cn.steam.foundation.common.model.CommonConstant.COMMON_MDC_PARAM_TRACE_ID;

/**
 * @author huangzz
 */
public class ServiceContextHolder {
    private static ThreadLocal<ServiceContext> threadLocal = new ThreadLocal<ServiceContext>();

    public static ServiceContext getOrInitServiceContext() {
        ServiceContext serviceContext = threadLocal.get();
        if (serviceContext == null) {
            serviceContext = new ServiceContext();
            serviceContext.setSourceId("DEFAULT");
            serviceContext.setUserId("DEFAULT");
        }
        return serviceContext;
    }

    public static void destroyedServiceContext(){
        threadLocal.set(null);
    }

    private static ServiceContext initDefault() {
        return new ServiceContext();
    }


    private static ServiceContext convertServiceContextFromSecurityContext(){
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Object o = securityContext.getAuthentication().getPrincipal();

        System.out.println(o);
        Object principal = securityContext.getAuthentication().getPrincipal();
        System.out.println(principal);

        return null;
    }
    public static void destroyedRequestContext(){
        destroyedServiceContext();
        MDC.remove(COMMON_MDC_PARAM_TRACE_ID);
    }

}

